package com.tianma315.wx.service.impl;


import com.tianma315.core.common.exception.MessageException;
import com.tianma315.core.sys.dao.RoleDao;
import com.tianma315.core.sys.dao.UserDao;
import com.tianma315.core.sys.domain.RoleDO;
import com.tianma315.core.sys.domain.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class SocialUserDetailsServiceImpl implements SocialUserDetailsService {

    @Autowired
    private UserDao userMapper;
    @Autowired
    private RoleDao roleMapper;


    @Override
    public SocialUserDetails loadUserByUserId(String s) throws UsernameNotFoundException {
        UserDO user = userMapper.selectEnableByUsername(s);
        if (user == null)
            throw new UsernameNotFoundException("您登录的账号不存在或已被冻结");

        //
        List<RoleDO> roles = roleMapper.selectByUserId(user.getId());
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        if (roles != null) {
            for (RoleDO role : roles) {
                authorities.add(role::getRoleName);
            }
        }

        //判断当前账号是否是商户号
        boolean isMerchant = false;
        for (RoleDO role : roles) {
            if ("ROLE_WAREHOUSE".equals(role.getRoleName())) {
                isMerchant = true;
                break;
            }
        }
        if (!isMerchant)
            throw new MessageException("您登录的账号不是发货员");

        return new SocialUser(user.getUsername(), user.getPassword(), authorities);
    }
}
